package com.butterfly.hotkey.dashboard.biz.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.butterfly.hotkey.common.exception.Asserts;
import com.butterfly.hotkey.dashboard.biz.convert.UserConvert;
import com.butterfly.hotkey.dashboard.biz.entity.User;
import com.butterfly.hotkey.dashboard.biz.exception.UserExceptionCode;
import com.butterfly.hotkey.dashboard.biz.mapper.UserMapper;
import com.butterfly.hotkey.dashboard.biz.service.UserService;
import com.butterfly.hotkey.dashboard.biz.vo.user.LoginRepVO;
import com.butterfly.hotkey.dashboard.biz.vo.user.LoginReqVO;
import com.butterfly.hotkey.dashboard.biz.vo.user.UserVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author butterfly
 * @since 2025/2/23
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public LoginRepVO login(LoginReqVO reqVO) {
        // 校验账号是否存在
        String username = reqVO.getUsername();
        User user = userMapper.selectLoginUser(username);
        Asserts.notNull(user, UserExceptionCode.LOGIN_ERROR);

        // 校验密码是否正确
        String password = reqVO.getPassword();
        boolean bcryptCheck = DigestUtil.bcryptCheck(password, user.getPwd());
        Asserts.isTrue(bcryptCheck, UserExceptionCode.LOGIN_ERROR);

        // 记录登录信息
        LoginRepVO repVO = new LoginRepVO();
        StpUtil.login(user.getId());
        repVO.setAccessToken(StpUtil.getTokenValue());
        return repVO;
    }

    @Override
    public UserVO getUserDetail(long loginId) {
        User user = userMapper.selectById(loginId);
        Asserts.notNull(user, UserExceptionCode.USER_NOT_FOUND);

        return UserConvert.INSTANCE.convert(user);
    }
}
